<template>
  <div class='app-container'>
    <el-card>
      <el-row>
        <el-col :span='24'>
          <el-form ref='formInline' :inline='true' :model='formInline' size='mini' class='formHeight'>
            <el-form-item :label="$t('role.name')" prop='name'>
              <el-input v-model='formInline.name' :placeholder="$t('role.name')" />
            </el-form-item>
            <el-form-item :label="$t('common.createTime')" prop='time'>
              <el-date-picker
                v-model='formInline.time'
                type='datetimerange'
                :picker-options='pickerOptions'
                range-separator='~'
                :start-placeholder="$t('common.startTime')"
                :end-placeholder="$t('common.endTime')"
                align='right'
              />
            </el-form-item>
            <el-form-item>
              <el-button type='primary' @click='onSubmit'>{{ $t('common.search') }}</el-button>
              <el-button @click="resetForm('formInline')">{{ $t('common.reset') }}</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>

    <el-card class='box-card mt20'>
      <div slot='header' class='clearfix'>
        <span>角色列表</span>
        <el-button
          size='mini'
          v-permission="'role.create'"
          style='float: right;'
          type='primary'
          icon='el-icon-circle-plus-outline'
          @click='createVisibleShow'
        >
          {{ $t('common.create') }}
        </el-button>
      </div>
      <el-row :gutter='20'>
        <el-col :span='24'>
          <el-table
            highlight-current-row
            :data='tableData'
            style='width: 100%'
            :default-sort='{prop: sort, order: order}'
            @sort-change='tableSortChange'
            size='mini'
          >
            <el-table-column prop='name' :label="$t('role.name')" sortable align='center' width='300' />
            <el-table-column prop='created_at' :label="$t('common.createdAt')" :formatter='rTime' sortable
                             align='center'
            />
            <el-table-column prop='updated_at' :label="$t('common.updatedAt')" :formatter='rTime' sortable
                             align='center'
            />
            <el-table-column :label="$t('common.handle')" class='editButton' align='center'>
              <template slot-scope='scope'>
                <el-button
                  size="mini"
                 v-if="scope.row.is_super!=1" 
                  v-permission="'role.syncPermissions'"
                  icon='el-icon-setting'
                  type='primary'
                  @click='syncPermissions(scope.row)'
                >
                  {{ $t('role.syncPermissions') }}
                </el-button>
                <el-button
                  v-if="scope.row.is_super!=1" 
                  size="mini"
                  v-permission="'role.update'"
                  icon='el-icon-edit-outline'
                  type='primary'
                  @click='handleEdit(scope.row)'
                >
                  {{ $t('common.update') }}
                </el-button>
                <el-popconfirm
                 
                  v-if="scope.row.is_super!=1" 
                  v-permission="'role.delete'"
                  :title="$t('common.confirmDelete')"
                  :confirm-button-text="$t('common.confirmButtonText')"
                  :cancel-button-text="$t('common.cancelButtonText')"
                  @onConfirm='handleDelete(scope.row.id)'
                >
                  <el-button
                    size='mini'
                    slot='reference'
                    icon='el-icon-delete'
                    type='danger'
                  >
                    {{ $t('common.delete') }}
                  </el-button>
                </el-popconfirm>

                  <el-button
                  size="mini"
                  v-permission="'role.syncPermissions'"
                  icon="el-icon-setting"
                  type="info"
                  v-if="scope.row.is_super==1"
                >
                  {{ $t('role.syncPermissions') }}
                </el-button>
                <el-button
                  v-if="scope.row.is_super==1"

                  size="mini"
                  v-permission="'role.update'"
                  icon="el-icon-edit-outline"
                  type="info"

                >
                  {{ $t('common.update') }}
                </el-button>
                  <el-button
                    v-if="scope.row.is_super==1"
                    size="mini"
                    slot="reference"
                    icon="el-icon-delete"
                    type="info"
                  >
                    {{ $t('common.delete') }}
                  </el-button>
               


              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span='24'>
<!--          <el-pagination-->
<!--            class='paginationPage'-->
<!--            :page-sizes='[10, 20,30]'-->
<!--            :page-size='limit'-->
<!--            :current-page='offset'-->
<!--            layout='total, sizes, prev, pager, next, jumper'-->
<!--            :total='total'-->
<!--            @size-change='handleSizeChange'-->
<!--            @current-change='handleCurrentChange'-->
<!--          />-->
          <pagination style="float: right;" v-show="total>0" :total="total" :page.sync="offset" :limit.sync="limit" @pagination="getRoles" />
        </el-col>
      </el-row>
    </el-card>
    <el-dialog
      v-el-drag-dialog
      :title="$t('common.create')"
      :visible.sync='createVisible'
    >
      <el-form ref='createForm' :model='createForm' label-width='auto' @submit.native.prevent size='mini'>
        <el-form-item label='角色身份' prop='name' :error="createError.is_admin  ? createError.is_admin [0] : ''">
          <el-radio-group v-model='createForm.is_admin'>
            <el-radio :label='1'>普通管理员</el-radio>
            <el-radio :label='2'>运维管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('role.name')" prop='name' :error="createError.name ? createError.name[0] : ''">
          <el-input v-model='createForm.name' />
        </el-form-item>
        <el-form-item>
          <el-button type='primary' :loading='createLoading' @click="onCreate('createForm')">{{
              $t('common.submit')
            }}
          </el-button>
          <el-button @click="resetCreateForm('createForm')">{{ $t('common.reset') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <el-dialog
      v-el-drag-dialog
      :title="$t('common.update')"
      :visible.sync='updateVisible'
    >
      <el-form ref='updateForm' :model='updateForm' label-width='auto' @submit.native.prevent>
        <el-form-item label='角色身份' prop='name' :error="updateError.is_admin  ? updateError.is_admin [0] : ''">
          <el-radio-group v-model='updateForm.is_admin'>
            <el-radio :label='1'>普通管理员</el-radio>
            <el-radio :label='2'>运维管理员</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="$t('role.name')" prop='name' :error="updateError.name ? updateError.name[0] : ''">
          <el-input v-model='updateForm.name' />
        </el-form-item>
        <el-form-item>
          <el-button type='primary' :loading='updateLoading' @click="onUpdate('updateForm')">{{
              $t('common.submit')
            }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <el-dialog
      :title='syncPermissionsTitle'
      :visible.sync='syncPermissionsVisible'
    >

      <sync-permissions :syncPermissionsIsadmin="syncPermissionsIsadmin" :id="syncPermissionsId" :success="success" />
    </el-dialog>
  </div>
</template>

<script>
import { rTime } from '@/utils'
import { roles, role, create, update, deleted } from '@/api/role'
import SyncPermissions from '@/views/role/syncPermissions'

export default {
  name: 'Roles',
  components: { SyncPermissions },
  data() {
    return {
      createForm: {
        name: '',
        guard_name: 'admin',
        is_admin: '',
      },
      updateForm: {
        name: '',
        guard_name: 'admin',
        is_admin: '',
      },
      formInline: {
        name: '',
        time: '',
      },
      total: 0,
      loading: true,
      order: 'descending',
      sort: 'created_at',
      offset: 0,
      limit: 10,
      tableData: [],
      pickerOptions: {
        shortcuts: [{
          text: this.$t('common.week'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          },
        }, {
          text: this.$t('common.oneMonth'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          },
        }, {
          text: this.$t('common.threeMonth'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          },
        }],
      },
      createError: {},
      updateError: {},
      syncPermissionsVisible: false,
      syncPermissionsId: 0,
      syncPermissionsTitle: '',
      syncPermissionsIsadmin:'',
      createVisible: false,
      updateVisible: false,
      createLoading: false,
      updateLoading: false,
    }
  },
  mounted() {
    this.getRoles()
  },
  methods: {
    onUpdate(formName) {
      this.updateError = {}
      this.updateLoading = true
      update(this.updateForm).then(response => {
        this.$message({
          message: response.message,
          type: 'success',
        })
        this.updateVisible = false
        this.getRoles()
      }).catch(reason => {
        const { data } = reason.response
        if (data.code === 422) {
          this.updateError = data.data
        }
      }).finally(() => {
        this.updateLoading = false
      })
    },
    createVisibleShow() {
      this.createVisible = true
    },
    onCreate(formName) {
      this.createError = {}
      this.createLoading = true
      create(this.createForm).then(response => {
        this.$message({
          message: response.message,
          type: 'success',
        })
        this.resetCreateForm(formName)
        this.createVisible = false
        this.offset = 0
        this.getRoles()
      }).catch(reason => {
        const { data } = reason.response
        if (data.code === 422) {
          this.createError = data.data
        }
      }).finally(() => {
        this.createLoading = false
      })
    },
    resetCreateForm(formName) {
      this.$refs[formName].resetFields()
    },
    onSubmit() {
      this.offset = 0
      this.getRoles()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.offset = 0
      this.getRoles()
    },
    tableSortChange(column) {
      this.order = column.order ? column.order : 'descending'
      this.sort = column.prop
      this.offset = 0
      this.getRoles()
    },
    getRoles() {
      this.loading = true
      const requestData = {
        offset: this.offset,
        limit: this.limit,
        order: this.order,
        sort: this.sort,
        name: this.formInline.name,
        guard_name: 'admin',
      }
      if (rTime(this.formInline.time[0]) !== '') {
        requestData['start_at'] = rTime(this.formInline.time[0])
      }
      if (rTime(this.formInline.time[1]) !== '') {
        requestData['end_at'] = rTime(this.formInline.time[1])
      }
      roles(requestData).then(response => {
        const { data } = response
        this.loading = false
        this.tableData = data.roles
        this.total = data.total
      }).catch(reason => {
        this.loading = false
        this.tableData = []
        this.total = 0
      })
    },
    handleSizeChange(val) {
      this.limit = val
      this.getRoles()
    },
    handleCurrentChange(val) {
      this.offset = val
      this.getRoles()
    },
    rTime(row, column) {
      return rTime(row[column.property])
    },
    handleDelete(id) {
      deleted({
        id: id,
      }).then(response => {
        this.$message({
          message: response.message,
          type: 'success',
        })
        this.getRoles()
      })
    },
    handleEdit(row) {
      role({
        id: row.id,
      }).then(response => {
        this.updateError = {}
        const { data } = response
        this.updateVisible = true
        this.updateForm = data
      })
    },
    syncPermissions(row) {
      console.log('权限设置')
      const { id, name,is_admin } = row
      this.syncPermissionsId = id
      this.syncPermissionsIsadmin=is_admin
      this.syncPermissionsVisible = true
      this.syncPermissionsTitle = name
    },
    success() {
      this.syncPermissionsId = 0
      this.syncPermissionsVisible = false
    },
  },
}
</script>

<style scoped>
.formHeight {
  height: 40px;
}
</style>
